<?php
/**
 *  统计事件人次
 * @author: jiangyong<jiangyong.go@qq.com>
 * @Date: 2023/5/26 16:01
 */


//$filename = 'origin/城主5月31日打点.csv';
//$wfile = "dest/城主5月31日打点统计.csv";


include_once "source.php";

$originfile = 'origin/*.csv';
$destDir = 'dest/';

foreach (glob($originfile) as $filename) {
    //echo "$filename size " . filesize($filename) . "\n";
    $path_parts = pathinfo($filename);
    $name = $path_parts['filename'];
    $wfile = $destDir . $name . '事件统计.csv';
    echo $wfile, "\n";
    saveCsvData($filename, $wfile);
}

function saveCsvData($filename, $wfile)
{
    $list = getCsvData($filename);
    $fp = fopen($wfile, 'w');
    $fields = ['source', 'source_name', 'number'];
    fputcsv($fp, $fields);
    foreach ($list as $id => $item) {
        $fields = [$id, Source::SOURCE_NAME_LIST[$id],  count($item)];
        fputcsv($fp, $fields);
    }
    fclose($fp);
}


function getCsvData($filename)
{
    $momoIds = [];
    $list = [];
    $row = 0;
    if (($handle = fopen($filename, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000)) !== FALSE) {
        //while (($data = fgets($handle, 1000, ' ')) !== FALSE) {
            $num = count($data);
            $row++;
            //echo "<p> $num fields in line $row: <br /></p>\n";
            if (1 == $row) {
                $fields = $data;
                continue;
            }

            $info = [];
            for ($c=0; $c < $num; $c++) {
                $info[$fields[$c]] = $data[$c];
            }
            if (empty($list[$info['source']][$info['momo_id']])) {
                $list[$info['source']][$info['momo_id']] = 0;
            }
            $list[$info['source']][$info['momo_id']] += 1;
            $row++;

        }
        fclose($handle);
    }
    return $list;
}


